package com.imax.center.controller;

import com.alibaba.fastjson.JSON;
import com.imax.center.common.Result;
import com.imax.center.common.ResultCode;
import com.imax.center.config.JwtConfig;
import com.imax.center.domain.UserInfoDomain;
import com.imax.center.service.SystemLogService;
import com.imax.center.entity.SystemLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Api(tags = "认证接口")
@RestController
@RequestMapping("/api/auth")
@Slf4j
public class AuthController {

    @Autowired
    private JwtConfig jwtConfig;

    @Autowired
    private SystemLogService systemLogService;

    @ApiOperation(value = "获取Token", notes = "登录获取JWT认证token")
    @PostMapping("/getToken")
    public Result<String> getToken(@RequestBody UserInfoDomain userInfoDomain) {
        if (userInfoDomain == null) {
            return Result.error(ResultCode.PARAM_ERROR);
        }
        log.info("登录用户信息:{}", JSON.toJSONString(userInfoDomain));
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userInfoDomain.getUserId());
        claims.put("userName", userInfoDomain.getUserName());
        claims.put("avatar", userInfoDomain.getAvatar());
        claims.put("deptId", userInfoDomain.getDeptId());
        claims.put("deptName", userInfoDomain.getDeptName());
        claims.put("unitId", userInfoDomain.getUnitId());
        claims.put("unitName", userInfoDomain.getUnitName());
        claims.put("roles", userInfoDomain.getRoles());
        claims.put("powerCode", userInfoDomain.getPowerCode());
        
        String token = jwtConfig.createToken(claims);
        return Result.success(token, "登录成功");
    }

    @ApiOperation(value = "获取用户信息", notes = "通过token获取当前登录用户信息")
    @GetMapping("/getUserInfo")
    public Result<UserInfoDomain> getUserInfo(HttpServletRequest request) {
        // 获取客户端IP地址
        String clientIp = getClientIpAddress(request);
        
        // 获取User-Agent信息
        String userAgent = request.getHeader("User-Agent");
        
        // 获取请求的其他信息
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        String referer = request.getHeader("Referer");
        
        String userInfoStr = (String) request.getAttribute("userInfo");
        UserInfoDomain userInfo = Objects.requireNonNull(JSON.parseObject(userInfoStr, UserInfoDomain.class));
        // 保存系统日志
        SystemLog logEntity = new SystemLog();
        logEntity.setUserId(userInfo.getUserId());
        logEntity.setUserName(userInfo.getUserName());
        logEntity.setIp(clientIp);
        logEntity.setUserAgent(userAgent);
        logEntity.setUri(requestURI);
        logEntity.setMethod(method);
        logEntity.setReferer(referer);
        logEntity.setCreateTime(LocalDateTime.now());
        systemLogService.save(logEntity);
        return Result.success(userInfo);
    }
    
    /**
     * 获取客户端真实IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 如果是多级代理，取第一个IP地址
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }
} 